package com.silverbox.waimai.dubboApi.order;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.silverbox.core.util.Arith;
import com.silverbox.core.util.HttpUtil;
import com.silverbox.shopper.entity.ThirdUserInfo;
import com.silverbox.sweeporder.common.CommonConstants;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.controller.waimai.entryvo.CouponBaseDto;
import com.silverbox.sweeporder.controller.waimai.entryvo.CreateWaimaiEntryDto;
import com.silverbox.sweeporder.service.index.IndexService;
import com.silverbox.waimai.dubboApi.payMotion.PayMotionApi;
import com.silverbox.waimai.entity.*;
import com.silverbox.waimai.entity.extend.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.silverbox.core.annotation.DataSource;
import com.silverbox.core.exception.CoreException;
import com.silverbox.core.exception.CoreException.CoreExceptionCode;
import com.silverbox.core.util.StringUtils;
import com.silverbox.core.util.Utils;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;
import com.silverbox.waimai.common.SweepOrderUtils;
import com.silverbox.waimai.entity.GoodsCart;
import com.silverbox.waimai.entity.MsgRecord;
import com.silverbox.waimai.entity.ReceiptTimeoutWaimai;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.WaimaiBath;
import com.silverbox.waimai.entity.WaimaiItemDetail;
import com.silverbox.waimai.entity.WaimaiOperateRelated;
import com.silverbox.waimai.entity.WaimaiSerialnumber;
import com.silverbox.waimai.entity.WaimaiTimeRelated;
import com.silverbox.waimai.entity.extend.AlreadyGoods;
import com.silverbox.waimai.entity.extend.CopyGoods;
import com.silverbox.waimai.entity.extend.WaimaiExtend;
import com.silverbox.waimai.entity.extend.WaimaiItemExtend;
import com.silverbox.waimai.entity.extend.WaimaiParam;
import com.silverbox.waimai.service.goodscart.GoodsCartDetailService;
import com.silverbox.waimai.service.goodscart.GoodsCartService;
import com.silverbox.waimai.service.order.WaimaiItemDetailService;
import com.silverbox.waimai.service.order.WaimaiItemService;
import com.silverbox.waimai.service.order.WaimaiSerialnumberService;
import com.silverbox.waimai.service.order.WaimaiService;
import com.silverbox.waimai.thread.CommonThread;

@Service
@Transactional
@DataSource(name = DataSource.DATASOURCE_B)
public class WaimaiServiceApiImpl implements WaimaiServiceApi {

    private static Logger logger = LoggerFactory.getLogger(WaimaiServiceApiImpl.class);

    @Autowired
    private WaimaiService waimaiService;

    @Autowired
    private WaimaiItemService waimaiItemService;

    @Autowired
    private WaimaiItemDetailService waimaiItemDetailService;

    @Autowired
    private WaimaiSerialnumberService waimaiSerialnumberService;

    @Autowired
    private GoodsCartDetailService goodsCartDetailService;

    @Autowired
    private GoodsCartService goodsCartService;

    @Autowired
    private IndexService indexService;

    @Autowired
    private PayMotionApi payMotionApi;

    @Value("${coupon.url}")
    private String couponUrl;
    @Value("${server.url}")
    private String serverUrl;
    @Value("${marketing.url}")
    public String marketingUrl;

    @Override
    public void saveWaimai(WaimaiExtend waimai, ShopperConfigExtend shopperConfigExt, CreateWaimaiEntryDto createWaimaiEntryVO) {
        if (waimai == null) {
            throw new CoreException("waimai is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (waimai.getShopId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(waimai.getBuyerId())) {
            throw new CoreException("tableNo is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        GoodsCart goodsCart = new GoodsCart();
        goodsCart.setShopperId(waimai.getShopId());
        goodsCart.setMustOrder(null);
        if (!StringUtils.isEmpty(waimai.getTableNum())) {
            if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
                goodsCart.setBuyerId(waimai.getBuyerId());
            }
            goodsCart.setTableNo(waimai.getTableNum());
        } else {
            goodsCart.setBuyerId(waimai.getBuyerId());
        }
        // 先清空购物车明细（需要根据购物车关联购物车明细）
        goodsCartDetailService.removeGoodsCartDetail(goodsCart);
        // 清空购物车
        int delCount = goodsCartService.removeGoodsCart(goodsCart);
        logger.info("创建完订单清空购物车是否成功delCount=" + delCount + "++++++++清空购物车条件shopperId=" + goodsCart.getShopperId()
                + "tableNo=" + goodsCart.getTableNo() + "buyerId=" + goodsCart.getBuyerId());
        //在线订单要单独删除必选菜（buyerId 删除不了system_buyerId的商品）
        if (new Long(4).equals(waimai.getOuterSupportId())) {
            goodsCart.setBuyerId("system_" + goodsCart.getBuyerId());
            int delNeedCount = goodsCartService.removeGoodsCart(goodsCart);
            logger.info("=============delNeedCount=" + delNeedCount);
        }
        List<WaimaiItemExtend> items = waimai.getItems();

        // 新增订单
//        waimaiService.addWaimai(waimai);
        //获取优惠券优惠信息
        //TODO  20200707！！！备注：外卖模式优惠预咨询已放置createPickUpWaimai()用于起送价限制，下期计划优化统一放置于saveItem()。
        if(!Constants.orderOutSupportId.WAIMAI_ORDER.getValue().equals(waimai.getOuterSupportId())){
            waimai = calcPromotionPrice(waimai.getItems(), waimai, createWaimaiEntryVO, shopperConfigExt);
        }

        waimai.setInsertTime(new Date());
        waimaiService.addWaimai(waimai);
        //更新优惠信息
//        waimaiService.updateWaimai(waimai);
        // 新增订单项
        List<WaimaiItemDetail> details = new ArrayList<WaimaiItemDetail>();
        for (WaimaiItemExtend item : items) {
            item.setWaimaiId(waimai.getId());
            waimaiItemService.addWaimaiItem(item);

            if (!CollectionUtils.isEmpty(item.getDetails())) {
                for (WaimaiItemDetail detail : item.getDetails()) {
                    detail.setItemId(item.getId());
                    details.add(detail);
                }
            }
        }
        // 新增订单项明细
        if (!CollectionUtils.isEmpty(details)) {
            waimaiItemDetailService.addWaimaiItemDetail(details);
        }

    }

    /*
     *<pre>
     * 说    明: 计算优惠价格信息
     * 涉及版本:
     * 创 建 者: YangYangjun
     * 日    期: 2020-04-17 11:36
     *</pre>
     **/
    @Override
    public WaimaiExtend calcPromotionPrice(List<WaimaiItemExtend> waimaiItems, WaimaiExtend waimai, CouponBaseDto couponBaseDto, ShopperConfigExtend shopperConfigExtend) {
        String memberId = couponBaseDto.getMemberId();
        Object vouchersObj = couponBaseDto.getVouchers();
        Integer isVip = Optional.ofNullable(couponBaseDto.getIsVip()).orElse(0);

        //是否享用会员价
        boolean isEnjoyMemberPrice = indexService.isEnjoyMemberPrice(couponBaseDto, shopperConfigExtend);

        List<Map<String, Object>> itemList = new LinkedList<>();
        if (waimaiItems != null) {
            for (WaimaiItemExtend item : waimaiItems) {
                //餐具费、打包盒不计入
                if ("cjf".equals(item.getGoodsDesc()) || "dbh".equals(item.getGoodsDesc())) {
                    continue;
                }
                HashMap<String, Object> itemMap = new HashMap<>();
                itemMap.put("buy_count", item.getBuyCount());
                itemMap.put("buy_price", !Utils.isEmpty(item.getMemberPrice()) && isEnjoyMemberPrice ? item.getMemberPrice() : item.getBuyPrice());
                itemMap.put("goods_id", item.getGoodsId());
                itemMap.put("goods_name", item.getGoodsName());
                itemMap.put("item_guid", item.getGuid());//
                //20200507 smo单品已优惠、方便预咨询计算全场
                itemMap.put("is_member_price", !Utils.isEmpty(item.getMemberPrice()) && isEnjoyMemberPrice ? 1 : 0);
                itemMap.put("original_price", !Utils.isEmpty(item.getMemberPrice()) && isEnjoyMemberPrice ? item.getMemberPrice() : item.getBuyPrice());
                itemMap.put("size_id", item.getSizeId());
                itemMap.put("coupon_code", item.getCouponCode());
                itemList.add(itemMap);
            }
        }

        HashMap<String, Object> orderMap = new HashMap<>();
        orderMap.put("is_out", waimai.getIsOut());
        orderMap.put("outer_support_id", waimai.getOuterSupportId());
        orderMap.put("people_number", waimai.getPeopleNumber());
        orderMap.put("total_amount", waimai.getTotalPrice());
        orderMap.put("order_num", waimai.getOrderNum());

        HashMap<String, Object> user = new HashMap<>();
        user.put("user_id", memberId);
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("invoke_source", "1802");
        paramsJson.put("item", itemList);
        paramsJson.put("order", orderMap);
        paramsJson.put("user", user);
        paramsJson.put("request_no", Utils.createOrderNum(waimai.getShopId()));
        paramsJson.put("store_id", waimai.getShopId());
        paramsJson.put("shop_id", waimai.getShopperId());
        paramsJson.put("is_pay_member", isVip);

        List<Map<String, Object>> vouchersListParam = new LinkedList<>();

        if (!Utils.isEmpty(vouchersObj)) {
            if (vouchersObj instanceof String) {
                String vouchersStr = (String) vouchersObj;
                for (String voucherUid : vouchersStr.split(",")) {
                    Map<String, Object> vouchersMap = new LinkedHashMap<>();
                    vouchersMap.put("uuid", voucherUid);
                    vouchersListParam.add(vouchersMap);
                }
                //优惠券信息
                paramsJson.put("voucher", vouchersListParam);
            } else if (vouchersObj instanceof List) {
                List vouchersList = (List) vouchersObj;
                for (Object voucherUid : vouchersList) {
                    Map<String, Object> vouchersMap = new LinkedHashMap<>();
                    vouchersMap.put("uuid", voucherUid);
                    vouchersListParam.add(vouchersMap);
                }
                //优惠券信息
                paramsJson.put("voucher", vouchersListParam);
            }
        }
        logger.info("优惠券预咨询请求参数：" + paramsJson.toJSONString());
        long start = System.currentTimeMillis();
        String resultString = HttpUtil.doPost(marketingUrl + "/promotion/consult", paramsJson);
        logger.info("预咨询请求耗时：" + (System.currentTimeMillis() - start));
        String responseLogJsonString = null;
        if (resultString != null) {
            JSONObject resultJson = JSONObject.parseObject(resultString);
            if ("10000".equals(resultJson.getString("code"))) {
                JSONObject dataJson = resultJson.getJSONObject("data");
                //原价
                String original_price = dataJson.getString("original_price");
                //优惠金额
                String promotion_price = dataJson.getString("promotion_price");
                promotion_price = Utils.isEmpty(promotion_price) ? "0" : promotion_price;

                //计算后总价
                String total_price = dataJson.getString("total_price");
                total_price = Utils.isEmpty(total_price) ? waimai.getTotalPrice().toString() : total_price;
                //优惠券使用列表
                //                JSONArray voucher_list = dataJson.getJSONArray("voucher_list");
                //                if(Double.valueOf(promotion_price) > 0){
                logger.info("优惠前waiami信息:{}", waimai.toString());
                //优惠需要排除餐盒、打包、配送等费用信息
                double otherPrice = Utils.isEmpty(waimai.getOtherPrice()) ? 0 : waimai.getOtherPrice();
                waimai.setTotalPrice(Arith.add(Double.valueOf(total_price), otherPrice));
                waimai.setPromotionPrice(Double.valueOf(promotion_price));
                logger.info("优惠后waiami信息:{}", waimai.toString());
                //订单优惠信息
                JSONArray orderPromotionArray = dataJson.getJSONArray("order_promotion");
                if (orderPromotionArray != null && orderPromotionArray.size() > 0) {
//                        JSONObject orderPromotionJson = JSONObject.parseObject(orderPromotionArray.get(0).toString());
//                        String uuid = orderPromotionJson.getString("uuid");
                    //                    String promotion_name = orderPromotionJson.getString("promotion_name");
                    //                    waimai.setPromotionName(promotion_name);
                    waimai.setPromotionPrice(Arith.sub(waimai.getOriginalPrice(), waimai.getTotalPrice()));

                    JSONObject uuidJson = new JSONObject();
                    List<String> uuidList = new LinkedList<>();

                    //优惠券使用情况,如果有使用优惠券则存储优惠券
                    logger.info("orderPromotionArray = " + orderPromotionArray);
                    for (Object orderPromotionObj : orderPromotionArray) {
                        JSONObject orderPromotionJson = JSONObject.parseObject(orderPromotionObj.toString());
                        String uuid = orderPromotionJson.getString("uuid");
                        if(!Utils.isEmpty(uuid)){
                            uuidList.add(uuid);
                        }
                    }
                    if(!Utils.isEmpty(uuidList)){
                        uuidJson.put("uuidArray", uuidList);
                        //暂存uuid优惠券ID用于核销 20200615
                        waimai.setExtendParams(uuidJson.toJSONString());
                    }
                }
                JSONObject responseLogJson = new JSONObject();
                responseLogJson.putAll(resultJson);
                //日志打印，voucher_list实在太多
//                responseLogJson.getJSONObject("data").remove("voucher_list");
                responseLogJsonString = responseLogJson.toJSONString();
            } else {
                responseLogJsonString = resultString;
            }
        }

        logger.info("优惠券预咨询返回参数：" + responseLogJsonString);
        return waimai;
    }

    @Override
    public void updateWaimaiItem(WaimaiItem item) {
        waimaiItemService.updateWaimaiItem(item);
    }

    @Override
    public Map<String, Object> findAllOrders(String appId, String storeName, Integer outSupportId, Integer pageNo, Integer pageSize, List<String> buyerId) {
        return waimaiService.findAllOrders(appId, storeName, outSupportId, pageNo, pageSize, buyerId);
    }

    @Override
    public List<WaimaiExtend> getWaimaiByBuyerIdInUnPaidEffective(String buyerId) {
        return waimaiService.getWaimaiByBuyerIdInUnPaidEffective(buyerId);
    }

    @Override
    public Waimai getWaimaiByOrderNum(String orderNum) {
        if (orderNum == null) {
            throw new CoreException("orderNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getWaimaiByOrderNum(orderNum);
    }

    @Override
    public int updateWaimai(Waimai waimai) {
        if (waimai == null) {
            throw new CoreException("waimai is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.updateWaimai(waimai);
    }

    @Override
    public WaimaiExtend getWaimaiAndDetailByOrderNum(String orderNum) {
        if (orderNum == null) {
            throw new CoreException("orderNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getWaimaiAndDetailByOrderNum(orderNum);
    }

    @Override
    public Waimai getWaimaiByBuyerId(WaimaiParam waimaiParam) {
        if (waimaiParam.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (waimaiParam.getBuyerId() == null) {
            throw new CoreException("buyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getWaimai(waimaiParam);
    }

    @Override
    public Waimai getWaimaiByTableNum(WaimaiParam waimaiParam) {
        if (waimaiParam.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (waimaiParam.getTableNum() == null) {
            throw new CoreException("tableNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getWaimai(waimaiParam);
    }

    @Override
    public Waimai getPreparationWaimaiByBuyerId(WaimaiParam waimaiParam) {
        return waimaiService.getPreparationWaimai(waimaiParam);
    }

    @Override
    public Waimai getPreparationWaimaiByTableNum(WaimaiParam waimaiParam) {
        return waimaiService.getPreparationWaimai(waimaiParam);
    }

    @Override
    public Waimai getUnfinishWaimaiByBuyerId(WaimaiParam waimaiParam) {
        return waimaiService.getWaimai(waimaiParam);
    }

    @Override
    public Waimai getUnfinishWaimaiByTableNum(WaimaiParam waimaiParam) {
        return waimaiService.getWaimai(waimaiParam);
    }

    @Override
    public WaimaiExtend getWaimaiAndDetailByBuyerId(WaimaiParam waimaiParam) {
        return waimaiService.getWaimaiAndDetail(waimaiParam);
    }

    @Override
    public WaimaiExtend getWaimaiAndDetailByTableNum(WaimaiParam waimaiParam) {
        return waimaiService.getWaimaiAndDetail(waimaiParam);
    }

    @Override
    public WaimaiExtend getWaimaiAndDetailByTableNumAndBuyerId(WaimaiParam waimaiParam) {
        return waimaiService.getWaimaiAndDetail(waimaiParam);
    }

    @Override
    public List<WaimaiExtend> getHistoryWaimaiList(WaimaiParam param) {
        if (param.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(param.getBuyerId())) {
            throw new CoreException("buyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getPageCount() == null) {
            throw new CoreException("pageCount is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getOutSupportId() == null) {
            throw new CoreException("outSupportId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getHistoryWaimaiList(param);
    }

    @Override
    public void addDish(WaimaiExtend waimaiExtend, List<WaimaiItemExtend> oldItems, CreateWaimaiEntryDto createWaimaiEntryVO, ShopperConfigExtend shopperConfigExtend) {
        if (waimaiExtend == null) {
            throw new CoreException("waimaiExtend is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        Waimai waimai = new Waimai();
        BeanUtils.copyProperties(waimaiExtend, waimai);
        //获取优惠券优惠信息
        List<WaimaiItemExtend> promotionItems;
        if (!Utils.isEmpty(oldItems)) {
            oldItems.addAll(waimaiExtend.getItems());
            promotionItems = oldItems;
        } else {
            promotionItems = waimaiExtend.getItems();
        }
        logger.info("oldItems = "+oldItems);
        logger.info("promotionItems = "+promotionItems);
        waimai = calcPromotionPrice(promotionItems, waimaiExtend, createWaimaiEntryVO, shopperConfigExtend);

        // 20200610 会员使用会员积分服务
//        double totalPay = payMotionApi.consumePointsInit(waimai,createWaimaiEntryVO.getIsConsumePoints());
//        waimai.setTotalPrice(totalPay);

        // 更新订单
        waimaiService.updateWaimai(waimai);
        //删除餐具费、打包费订单项
        waimaiService.deleteBagOrBoxItemByWaimaiId(waimaiExtend.getId());
        // 更新订单项(加菜状态)
        waimaiService.updateWaimaiItem(waimaiExtend.getId());
        // 新增订单项
        List<WaimaiItemDetail> details = new ArrayList<WaimaiItemDetail>();
        List<WaimaiItemExtend> items = waimaiExtend.getItems();
        for (WaimaiItemExtend item : items) {
            waimaiItemService.addWaimaiItemForAddFish(item);
            if (!CollectionUtils.isEmpty(item.getDetails())) {
                for (WaimaiItemDetail detail : item.getDetails()) {
                    detail.setItemId(item.getId());
                    details.add(detail);
                }
            }
        }
        // 新增订单项明细
        if (!CollectionUtils.isEmpty(details)) {
            waimaiItemDetailService.addWaimaiItemDetail(details);
        }
    }

    @Override
    public List<WaimaiSerialnumber> getWaimaiSerialnumberByOrderNum(String orderNum) {
        if (Utils.isEmpty(orderNum)) {
            throw new CoreException("orderNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiSerialnumberService.getWaimaiSerialnumberByOrderNum(orderNum);
    }

    @Override
    public int saveWaimaiSerialnumber(WaimaiSerialnumber record) {
        if (null == record) {
            throw new CoreException("record is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiSerialnumberService.saveWaimaiSerialnumber(record);
    }

    @Override
    public int deleteWaimaiSerialNumberByOutTradeNo(String outTradeNo) {
        return waimaiSerialnumberService.deleteWaimaiSerialNumberByOutTradeNo(outTradeNo);
    }

    @Override
    public void deleteOrderByIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new CoreException("ids is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        waimaiService.deleteOrderByIds(ids);
    }

    @Override
    public List<CopyGoods> getCopyGoods(Integer storeId, String tableUid, String startDate, String endDate) {
        if (storeId == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (tableUid == null) {
            throw new CoreException("tableUid is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (startDate == null) {
            throw new CoreException("startDate is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (endDate == null) {
            throw new CoreException("endDate is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getCopyGoods(storeId, tableUid, startDate, endDate);
    }

    @Override
    public void uploadOrder(Waimai waimai, String orderNum, String koubeiUploadUrl, String uploadOrderFlag, Long OuterSupportId) {
        if (waimai != null && "true".equals(uploadOrderFlag) && !new Long(103L).equals(OuterSupportId)) {
            //如果口碑门店
            if (StringUtils.isEmpty(waimai.getKoubeiShopid()) && waimai.getPayModel() != null
                    && !new Integer(8002).equals(waimai.getPayModel())
                    && !new Integer(11).equals(waimai.getOrderStatus())) {

            } else {
                Map<String, String> nameValuePair = new HashMap<String, String>();
                nameValuePair.put("orderNum", orderNum);
                try {
                    CommonThread.execute("=========开始上传口碑订单=========", koubeiUploadUrl + "/alipayUpload/uploadOrder.htm",
                            nameValuePair);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("上传订单失败===========" + "订单号：" + orderNum);
                }
                logger.info("上传订单日志===========" + "订单号：" + orderNum + "");
            }
        }
    }

    @Override
    public void sendServiceWindowMsg(Waimai waimai, String alipayUserId, String nick, String address, String sweepUrl,
                                     String serviceWindowUrl, String msgType) {
        logger.info("进入发消息：" + waimai.getOuterSupportId() + "," + alipayUserId);
        if (null != waimai && !Utils.isEmpty(waimai.getBuyerId()) && !Utils.isEmpty(alipayUserId)
                && !Utils.isEmpty(msgType)) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("msgType", msgType);
            map.put("toUserId", waimai.getBuyerId());
            map.put("alipayUserId", alipayUserId);
            String url = "";

            if (new Long(4).equals(waimai.getOuterSupportId()) || new Long(81).equals(waimai.getOuterSupportId())) {
                url = sweepUrl + "/alipayAuth/auth.htm?shopperId=" + waimai.getShopId() + "&orderNum="
                        + waimai.getOrderNum() + "&page=myOrder&openPay=0&outerSupportId=4&buyerId=" + waimai.getBuyerId();
                map.put("url", url);
                if ("1".equals(msgType)) { // 消息类型为订单提醒
                    map.put("actionName", "查看详情");
                    map.put("first", "您好,您已消费成功。");
                    map.put("remark", "为避免影响口感，请尽快前往取餐！");
                    map.put("keyword1", SweepOrderUtils
                            .getOrderSeq(null == waimai.getOrderSeq() ? "" : (waimai.getOrderSeq() + "")));
                    map.put("keyword2", nick);
                    map.put("keyword3", address);
                    map.put("keyword4", waimai.getTotalPay() + "");
                    map.put("keyword5", Utils.isEmpty(waimai.getReachTime()) ? "无" : waimai.getReachTime());
                    logger.info("=====推送支付宝生活号消息参数：" + map.toString());

                    CommonThread.execute("==========推送支付宝生活号订单提醒：" + waimai.getOrderNum(),
                            serviceWindowUrl + "/msg/sendTemplateMsg.htm", map);
                }
            } else if (new Long(5).equals(waimai.getOuterSupportId())) {
                // 结账通知
                if ("3".equals(msgType)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
                    url = sweepUrl + "/alipayAuth/auth.htm?shopperId=" + waimai.getShopId() + "&orderNum="
                            + waimai.getOrderNum() + "&page=myOrder&openPay=0&outerSupportId=5&tableUid="
                            + waimai.getTableUid() + "&buyerId=" + waimai.getBuyerId();
                    map.put("url", url);
                    map.put("actionName", "查看详情");
                    map.put("first", "消费订单");
                    map.put("remark", "订单已完结，欢迎下次光临！");
                    map.put("keyword1", "已结账");
                    map.put("keyword2", Utils.isEmpty(waimai.getTableNum()) == true ? "" : waimai.getTableNum());
                    map.put("keyword3", waimai.getPeopleNumber() == null ? "1" : waimai.getPeopleNumber().toString());
                    map.put("keyword4", waimai.getTotalPay() == null ? "" : waimai.getTotalPay().toString());
                    map.put("keyword5", waimai.getPayTime() == null ? "" : sdf.format(waimai.getPayTime()));
                    logger.info("=====msgType=3,推送支付宝生活号消息参数：" + map.toString());
                    CommonThread.execute("==========msgType=3,推送支付宝生活号结账通知：" + waimai.getOrderNum(),
                            serviceWindowUrl + "/msg/sendTemplateMsg.htm", map);
                }
            }
        }
    }

    @Override
    public void deleteOrderByOrderNum(List<String> orderNums) {
        if (CollectionUtils.isEmpty(orderNums)) {
            throw new CoreException("orderNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        waimaiService.deleteOrderByOrderNum(orderNums);
    }

    @Override
    public int updateWaimaiByCleanTable(WaimaiParam waimai) {
        if (waimai == null) {
            throw new CoreException("waimai is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (waimai.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(waimai.getTableUid())) {
            throw new CoreException("tableUid is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.updateWaimaiByCleanTable(waimai);
    }

    @Override
    public List<AlreadyGoods> getAlreadyGoods(Integer storeId, Long thirdUserInfoId, String createDate) {
        if (storeId == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (thirdUserInfoId == null) {
            throw new CoreException("buyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(createDate)) {
            throw new CoreException("createDate is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getAlreadyGoods(storeId, thirdUserInfoId, createDate);
    }

    @Override
    public List<WaimaiExtend> getOnlineOrderHexiao(WaimaiParam param) {
        if (param == null) {
            throw new CoreException("param is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(param.getBuyerId())) {
            throw new CoreException("buyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getIsHexiao() == null) {
            throw new CoreException("isHexiao is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getOutSupportId() == null) {
            throw new CoreException("outSupportId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getOnlineOrderHexiao(param);
    }

    @Override
    public List<WaimaiExtend> getOnlineMealOrder(WaimaiParam param) {
        if (param == null) {
            throw new CoreException("param is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getOnlineMealOrder(param);
    }

    @Override
    public int updateWaimaiIdOrNum(WaimaiParam param) {
        if (param == null) {
            throw new CoreException("param is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (CollectionUtils.isEmpty(param.getOrderNum())) {
            throw new CoreException("orderNum is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.updateWaimaiIdOrNum(param);
    }

    @Override
    public int saveAndUpdateWaimaiTimeRelated(WaimaiTimeRelated timeRelated) {
        if (timeRelated == null) {
            throw new CoreException("timeRelated is null  创建修改订单操作相关时间参数异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (timeRelated.getId() != null) {
            waimaiService.updateWaimaiTimeRelated(timeRelated);
        } else {
            waimaiService.saveWaimaiTimeRelated(timeRelated);
        }
        return 0;
    }

    @Override
    public int updateWaimaiByOrderNum(Waimai param) {
        return waimaiService.updateWaimaiByOrderNum(param);
    }

    @Override
    public int saveOrUpdateWaimaiBath(WaimaiBath waimaiBath) {
        if (waimaiBath == null) {
            throw new CoreException("waimaiBath is null  保存订单批次号信息异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.saveOrUpdateWaimaiBath(waimaiBath);
    }

    @Override
    public int saveReceiptTimeoutWaimai(ReceiptTimeoutWaimai receiptWaimai) {
        if (receiptWaimai == null) {
            throw new CoreException("waimaiBath is null  保存订单批次号信息异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.saveReceiptTimeoutWaimai(receiptWaimai);
    }

    @Override
    public ReceiptTimeoutWaimai getReceiptTimeoutWaimai(String orderNum) {
        if (StringUtils.isEmpty(orderNum)) {
            throw new CoreException("orderNum is null 查询订单超时记录表异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getReceiptTimeoutWaimai(orderNum);
    }

    @Override
    public WaimaiExtend getwaimaiBytakeMealCode(WaimaiParam param) {
        if (param == null) {
            throw new CoreException("param is null 取餐码获取订单信息异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(param.getTakeMealCode())) {
            throw new CoreException("takeMealCode is null 取餐码获取订单信息异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getStoreId() == null) {
            throw new CoreException("storeId is null 取餐码获取订单信息异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getWaimaiAndDetail(param);
    }

    @Override
    public int saveWaimaiOperateRelated(WaimaiOperateRelated waimaiOperateRelated) {
        if (waimaiOperateRelated == null) {
            throw new CoreException("waimaiOperateRelated is null  保存订单操作异常", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.saveWaimaiOperateRelated(waimaiOperateRelated);
    }

    private Double computeGoodsPrice(Double bagPrice, Integer isOut, Double totalBuyCount, List<GoodsCartAndDetail> goodsList) {
        Double packBuyCount = 0.0;
        Double packBuyPrice = 0.0;
        // 计算打包费
        if (bagPrice > 0 && !new Integer(1).equals(isOut)) {
            for (GoodsCartAndDetail goods : goodsList) {
                if ("打包".equals(goods.getGoodsDesc())) {
                    packBuyCount = Arith.add(packBuyCount, goods.getBuyCount());
                }
            }
            packBuyPrice = Arith.mul(bagPrice, packBuyCount);
        }
        if (isOut == 1 && bagPrice > 0) {
            packBuyPrice = Arith.mul(bagPrice, totalBuyCount);
        }
        return packBuyPrice;
    }

    @Override
    public void saveWaimaiOperateRelated(Waimai waimai, ThirdUserInfo thirdUserInfo, String timeType) {
        WaimaiOperateRelated operateRelated = new WaimaiOperateRelated();
        operateRelated.setShopId(waimai.getShopperId());
        operateRelated.setStoreId(waimai.getShopId());
        operateRelated.setOuterSupportId(waimai.getOuterSupportId());
        operateRelated.setOrderNum(waimai.getOrderNum());
        operateRelated.setOrderDate(waimai.getCreateTime());
        //TODO itemType
        operateRelated.setTimeType(timeType);
        //在订单项保存用户操作信息，区分是顾客还是服务员进行订单操作	add lxy 2019年3月19日
        if (!Utils.isEmpty(thirdUserInfo)) {
            operateRelated.setOperateTime(new Date());
            operateRelated.setOperatorType(CommonConstants.WaimaiOperatorType.CUSTOMER.getValue());
            operateRelated.setOperatorId(thirdUserInfo.getId());
            operateRelated.setOperatorNick(Utils.isEmpty(thirdUserInfo.getNickName()) ? "吃货" : thirdUserInfo.getNickName());
        }
        operateRelated.setCreateTime(new Date());
        saveWaimaiOperateRelated(operateRelated);
    }

    private void receiveCoupon(Integer shopperId, String userId, String disItemIds, String disItemTypes, String couponUrl) {
        Map<String, String> nameValuePair = new HashMap<String, String>();
        nameValuePair.put("shopperId", shopperId.toString());
        nameValuePair.put("userId", userId);
        nameValuePair.put("itemIds", disItemIds);
        nameValuePair.put("itemTypes", disItemTypes);
        String result = HttpUtil.buildRequest(couponUrl + "/kouberajax/benefitSend.htm", nameValuePair, 60000, 60000, "UTF-8");
        logger.info("领券日志：" + result);
    }

    private String changePropIds(String propIds) {
        if (Utils.isEmpty(propIds) || !propIds.contains("×")) {
            return propIds;
        }
        String[] propIdArr = propIds.split("\\+");
        String newPropIds = "";
        for (int i = 0; i < propIdArr.length; i++) {
            if (propIdArr[i].contains("×")) {
                newPropIds = ("".equals(newPropIds) ? "" : (newPropIds + "+")) + propIdArr[i].substring(0, propIdArr[i].lastIndexOf("×"));
            } else {
                newPropIds = ("".equals(newPropIds) ? "" : (newPropIds + "+")) + propIdArr[i];
            }
        }
        return newPropIds;
    }

    /**
     * 去掉propIds或者propNames的头尾+或_
     *
     * @param propStr
     * @return
     */
    private String changePropString(String propStr) {
        if (Utils.isEmpty(propStr)) {
            return propStr;
        }
        propStr = propStr.replaceAll("_", "+");
        if (propStr.startsWith("+")) {
            propStr = propStr.substring(1, propStr.length());
        }
        if (propStr.endsWith("+")) {
            propStr = propStr.substring(0, propStr.length() - 1);
        }
        propStr = propStr.replaceAll("x", "×");
        return propStr;
    }

    /**
     * 去掉propNames中的x（云POS接单，不需要在propdIds中拼接加料数量）
     *
     * @param propNames
     * @return
     */
    private String changePropNames(String propNames) {
        if (Utils.isEmpty(propNames)) {
            return propNames;
        }
        String[] propNameArr = propNames.split("\\+");
        String newPropNames = "";
        for (int i = 0; i < propNameArr.length; i++) {
            if (propNameArr[i].contains("×")) {
                String[] propNameAndCountArr = propNameArr[i].split("×");
                if (new Integer(1).equals(Integer.valueOf(propNameAndCountArr[1]))) {    //加料数量为1的时候，去掉x1
                    newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameAndCountArr[0];
                } else {
                    newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameArr[i];
                }
            } else {
                newPropNames = ("".equals(newPropNames) ? "" : (newPropNames + "+")) + propNameArr[i];
            }
        }
        return newPropNames;
    }

    public List<WaimaiExtend> getTodayOrderHexiaoOrDelivery(WaimaiParam param) {
        if (param == null) {
            throw new CoreException("param is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getStoreId() == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(param.getBuyerId())) {
            throw new CoreException("buyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (param.getOutSupportId() == null) {
            throw new CoreException("outSupportId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getTodayOrderHexiaoOrDelivery(param);
    }

    @Override
    public List<Waimai> getMyUnPayOrder(Integer storeId, String tableName, String buyerId) {
        if (storeId == null) {
            throw new CoreException("storeId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        if (StringUtils.isEmpty(tableName) && StringUtils.isEmpty(buyerId)) {
            throw new CoreException("tableNameAndbuyerId is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        return waimaiService.getMyUnPayOrder(storeId, tableName, buyerId);
    }

    @Override
    public void deleteUnpayHistoryOrderById(Long id) {
        if (id == null) {
            throw new CoreException("id is null", CoreExceptionCode.EXCP_PARAM_NULL);

        }
        waimaiService.deleteUnpayHistoryOrderById(id);
    }

    @Override
    public int saveMsgRecord(MsgRecord msgRecord) {
        return waimaiService.saveMsgRecord(msgRecord);
    }

    @Override
    public List<MsgRecord> selectMsgRecord(Integer storeId, Long machineId) {
        return waimaiService.selectMsgRecord(storeId, machineId);
    }

    @Override
    public void deleteMsgRecord(String msgCode) {
        if (StringUtils.isEmpty(msgCode)) {
            throw new CoreException("msgCode is null", CoreExceptionCode.EXCP_PARAM_NULL);
        }
        waimaiService.deleteMsgRecord(msgCode);
    }

    @Override
    public Map<String, Object> findAllOrdersByShop(Long shopId, String storeName, Integer outSupportId, Integer pageNo, Integer pageSize, List<String> buyerId) {
        return waimaiService.findAllOrdersByShop(shopId, storeName, outSupportId, pageNo, pageSize, buyerId);
    }
}
